package com.lx.video.web;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.lx.bilibili.entity.Danmu;
import com.lx.bilibili.entity.Video;
import com.lx.video.dao.DanmuMapper;
import com.lx.video.dao.VideoMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Set;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author lx
 * @since 2025-04-06
 */
@RestController
@RequestMapping("/danmu")
public class DanmuController {

    @Autowired
    DanmuMapper danmuMapper;

    @Resource
    private RedisTemplate<String, Danmu> redisTemplate;

    @Autowired
    VideoMapper videoMapper;


    @RequestMapping("savedanmu")
    public void savedanmu(@RequestBody Danmu danmu) {
        if(danmu.getUid() == null || "".equals(danmu.getUid())){
            return ;
        }
        System.out.println(danmu);
        danmu.setTime(new Timestamp(System.currentTimeMillis()));
        redisTemplate.opsForValue().set("danmu"+danmu.getUid() + System.currentTimeMillis(),danmu);
        Set<String> keys = redisTemplate.keys("danmu*");
        System.out.println("keys"+ keys);
    }

    @RequestMapping("getDanmuByVid")

    public List<Danmu> getDanmuByVid(int id) {
        LambdaQueryWrapper<Danmu> lqw = new LambdaQueryWrapper<>();
        lqw.eq(Danmu::getVid, id);
        return danmuMapper.selectList(lqw);
    }





    // 每3分钟执行一次
    @Scheduled(fixedRate = 180000)
    @Transactional
    public void scheduled() {
        List<Danmu> list = new ArrayList<>();
        Set<String> keys = redisTemplate.keys("danmu*");
        if (keys != null) {
            for (String key : keys) {
                Danmu value = redisTemplate.opsForValue().get(key);
                if (value != null) {
                    list.add(value);
                    // 可选：取出后删除数据，防止重复处理
                    redisTemplate.delete(key);
                }
            }
        }
        System.out.println("list" + list);
        for (Danmu danmu : list) {
            danmuMapper.insert(danmu);
            LambdaUpdateWrapper<Video> luw = new LambdaUpdateWrapper<>();
            luw.eq(Video::getId, danmu.getVid()).setSql("danmucount = danmucount + 1");
            videoMapper.update(luw);

        }
        System.out.println("弹幕数据存入数据库");
    }
}
